import datetime
import random
import time

import requests

from drissionDemo.proxies import ProxyPool
from generate_sql import *


def process_crs_(entry, id, crs_combination_desc):
    processed_results = {}
    for key, value in entry.items():
        if key.startswith("s-1"):

            if key == "s-1sd":
                processed_results["平其他"] = value
            elif key == "s-1sa":
                processed_results["负其他"] = value
            elif key == "s-1sh":
                processed_results["胜其他"] = value
        elif key.startswith("s") and not key.endswith("f") and value != "0":

            scores = key[1:].split("s")

            score_key = f"{int(scores[0])}:{int(scores[1])}"
            processed_results[score_key] = value
    sorted_results = dict(sorted(processed_results.items(), key=lambda item: (
        0 if item[0] == "胜其他" else
        1 if isinstance(item[0], str) and item[0].count(':') == 1 and int(item[0].split(':')[0]) > int(
            item[0].split(':')[1]) else
        2 if item[0] == "平其他" else
        3
    )))
    sorted_results['id'] = id
    sorted_results['flag'] = entry["flag"]
    sorted_results['crs_combination_desc'] = crs_combination_desc

    return sorted_results


def process_crs_list(crs_list, id, crs_combination_desc):
    crs_list_sorted = sorted(crs_list, key=lambda x: (x['updateDate'], x['updateTime']))
    if crs_list_sorted:
        first_entry = crs_list_sorted[0]
        if len(crs_list_sorted) == 1:
            first_entry1 = first_entry.copy()
            last_entry = first_entry.copy()
            first_entry1["flag"] = "N"
            last_entry["flag"] = "Y"
            比分固定奖金最终.append(process_crs_(first_entry1, id, crs_combination_desc))
            比分固定奖金最终.append(process_crs_(last_entry, id, crs_combination_desc))
        else:
            first_entry2 = crs_list_sorted[0]
            last_entry2 = crs_list_sorted[-1]
            first_entry2["flag"] = "N"
            last_entry2["flag"] = "Y"
            比分固定奖金最终.append(process_crs_(first_entry2, id, crs_combination_desc))
            比分固定奖金最终.append(process_crs_(last_entry2, id, crs_combination_desc))


def process_entry(entry):
    processed_results = {}
    for key, value in entry.items():
        if key.startswith("s") and not key.endswith("f") and value != "0":
            score_key = key[1:]
            processed_results[score_key] = value

    sorted_results = dict(sorted(processed_results.items(), key=lambda item: int(item[0])))

    publication_time = f"{entry['updateDate']} {entry['updateTime']}"
    sorted_results['publication_time'] = publication_time

    return sorted_results


def process_ttg_list(ttg_list, id, ttg_combination_desc):
    ttg_list_sorted = sorted(ttg_list, key=lambda x: (x['updateDate'], x['updateTime']))
    if ttg_list_sorted:
        first_entry2 = ttg_list_sorted[0]
        if len(ttg_list_sorted) == 1:
            first_entry3 = first_entry2.copy()
            last_entry3 = first_entry2.copy()
            first_entry_result = process_entry(first_entry3)
            first_entry_result["id"] = id
            first_entry_result["flag"] = "N"
            first_entry_result["ttg_combination_desc"] = ttg_combination_desc
            last_entry_result = process_entry(last_entry3)
            last_entry_result["id"] = id
            last_entry_result["flag"] = "Y"
            last_entry_result["ttg_combination_desc"] = ttg_combination_desc
            总进球固定奖金最终.append(json.dumps(first_entry_result, ensure_ascii=False, indent=4))
            总进球固定奖金最终.append(json.dumps(last_entry_result, ensure_ascii=False, indent=4))
        else:
            first_entry = ttg_list_sorted[0]
            last_entry = ttg_list_sorted[-1]

            first_entry_result = process_entry(first_entry)
            first_entry_result["id"] = id
            first_entry_result["flag"] = "N"
            first_entry_result["ttg_combination_desc"] = ttg_combination_desc
            last_entry_result = process_entry(last_entry)
            last_entry_result["id"] = id
            last_entry_result["flag"] = "Y"
            last_entry_result["ttg_combination_desc"] = ttg_combination_desc

            总进球固定奖金最终.append(json.dumps(first_entry_result, ensure_ascii=False, indent=4))
            总进球固定奖金最终.append(json.dumps(last_entry_result, ensure_ascii=False, indent=4))


def process_entry_hafu(entry):
    """
    处理单个总进球条目，提取有效数据并返回结果。
    """
    processed_results = {
        "胜胜": entry["hh"],
        "胜平": entry["hd"],
        "胜负": entry["ha"],
        "平胜": entry["dh"],
        "平平": entry["dd"],
        "平负": entry["da"],
        "负胜": entry["ah"],
        "负平": entry["ad"],
        "负负": entry["aa"]
    }

    publication_time = f"{entry['updateDate']} {entry['updateTime']}"
    processed_results['publication_time'] = publication_time
    processed_results['id'] = entry["id"]
    processed_results['flag'] = entry["flag"]
    processed_results['hafu_combination_desc'] = entry["hafu_combination_desc"]
    return processed_results


def process_hafu_list(hafu_list, id, hafu_combination_desc):
    hafu_list_sorted = sorted(hafu_list, key=lambda x: (x['updateDate'], x['updateTime']))

    if hafu_list_sorted:
        first_entry2 = hafu_list_sorted[0]
        if len(hafu_list_sorted) == 1:
            first_entry = first_entry2.copy()
            first_entry["id"] = id
            first_entry["flag"] = "N"
            first_entry["hafu_combination_desc"] = hafu_combination_desc
            last_entry = first_entry2.copy()
            last_entry["id"] = id
            last_entry["flag"] = "Y"
            last_entry["hafu_combination_desc"] = hafu_combination_desc

            半全场胜平负固定奖金最终.append(process_entry_hafu(first_entry))
            半全场胜平负固定奖金最终.append(process_entry_hafu(last_entry))
        else:
            first_entry = hafu_list_sorted[0]
            first_entry["id"] = id
            first_entry["flag"] = "N"
            first_entry["hafu_combination_desc"] = hafu_combination_desc
            last_entry = hafu_list_sorted[-1]
            last_entry["id"] = id
            last_entry["flag"] = "Y"
            last_entry["hafu_combination_desc"] = hafu_combination_desc

            半全场胜平负固定奖金最终.append(process_entry_hafu(first_entry))
            半全场胜平负固定奖金最终.append(process_entry_hafu(last_entry))


headers = {
    'accept': 'application/json, text/javascript, */*; q=0.01',
    'accept-language': 'zh-CN,zh;q=0.9',
    'origin': 'https://www.sporttery.cn',
    'priority': 'u=1, i',
    'referer': 'https://www.sporttery.cn/',
    'sec-ch-ua': '"Google Chrome";v="131", "Chromium";v="131", "Not_A Brand";v="24"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': '"Windows"',
    'sec-fetch-dest': 'empty',
    'sec-fetch-mode': 'cors',
    'sec-fetch-site': 'same-site',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
}

matchEndDate = datetime.datetime.today().strftime("%Y-%m-%d")

params = {
    'matchPage': '1',
    'matchBeginDate': '2025-03-25',
    'matchEndDate': '2025-04-11',
    'leagueId': '',
    'pageSize': '500',
    'pageNo': '1',
    'isFix': '0',
    'pcOrWap': '1',
}

pool = ProxyPool(
    username="d2002701022",
    password="b7zf0dk9",
    areas=('北京', '上海', '广东')
)

response = requests.get('https://webapi.sporttery.cn/gateway/jc/football/getMatchResultV1.qry', params=params,
                        headers=headers,
                        proxies=pool.get_proxies()
                        )
data = response.json()

matches_info = [
    {
        'matchId': match['matchId'],
        'leagueNameAbbr': match['leagueNameAbbr'],
        'matchDate': match['matchDate']
    }
    for match in data['value']['matchResult']
]
batch_size = 10


def get_combination_desc(match_result_list, flag):
    try:
        if match_result_list == []:
            return [-1]
        return [result['combinationDesc'] for result in match_result_list if result.get('code', [-1]) == flag]
    except KeyError:
        return [-1, -1]
    except Exception as e:
        print(f"An error occurred: {e}")
        return [-1, -1]


for batch_start in range(0, len(matches_info), batch_size):
    batch_matches = matches_info[batch_start:batch_start + batch_size]

    for match_info in batch_matches:

        match_id = match_info['matchId']
        detail_url = f'https://webapi.sporttery.cn/gateway/jc/fb/getMatchScoreV1.qry?matchId={match_id}'
        detail_response = ""
        try:
            detail_response = requests.get(detail_url, headers=headers, proxies=pool.get_proxies())
        except Exception as e:
            time.sleep(2)
            detail_response = requests.get(detail_url, headers=headers, proxies=pool.get_proxies())
        detail_data = ""

        if detail_response.status_code == 200:
            try:

                detail_data = detail_response.json()

                while detail_data.get('success') != True or detail_data.get('success') == None:
                    time.sleep(random.uniform(1, 5))
                    print(f"请求的 matchId {match_id} 返回失败")
                    detail_url = f'https://webapi.sporttery.cn/gateway/jc/fb/getMatchScoreV1.qry?matchId={match_id}'
                    detail_response = requests.get(detail_url, headers=headers, proxies=pool.get_proxies())
                    detail_data = detail_response.json()
            except requests.exceptions.JSONDecodeError as e:
                print("JSON解析失败，可能返回的不是合法的JSON格式")
                print("原始响应内容:", detail_response.text)
        else:
            print(f"错误的 matchId: {match_id}")
            print(f"请求失败，HTTP 状态码: {detail_response.status_code}")
            continue

        if detail_data == "":
            continue





        else:
            combined_data = detail_data['value']
            combined_data['leagueNameAbbr'] = match_info['leagueNameAbbr']
            combined_data['matchDate'] = match_info['matchDate']
            combined_data['source'] = '体彩'
            combined_data['id'] = match_id
        time.sleep(0.1)
        print(f"Combined Data for match {match_id}: {combined_data}")

        胜平负固定奖金初始 = []
        胜平负固定奖金最终 = []
        让胜平负固定奖金初始 = []
        让胜平负固定奖金最终 = []
        比分固定奖金初始 = []
        比分固定奖金最终 = []
        总进球固定奖金初始 = []
        总进球固定奖金最终 = []
        半全场胜平负固定奖金初始 = []
        半全场胜平负固定奖金最终 = []

        time.sleep(random.uniform(1, 3))
        params = {
            'clientCode': '3001',
            'matchId': match_info['matchId']
        }
        response = ""
        try:
            response = requests.get('https://webapi.sporttery.cn/gateway/jc/football/getFixedBonusV1.qry',
                                    params=params,
                                    headers=headers,
                                    proxies=pool.get_proxies())
        except Exception as e:
            time.sleep(2)
            response = requests.get('https://webapi.sporttery.cn/gateway/jc/football/getFixedBonusV1.qry',
                                    params=params,
                                    headers=headers,
                                    proxies=pool.get_proxies())
        detail_data = response.json()
        match_result_list = detail_data['value'].get('matchResultList', [])
        sectionsNo999 = detail_data['value'].get('sectionsNo999', [])
        if sectionsNo999 == "无效场次":
            continue
        insert_data(generate_data([combined_data]))

        try:
            had_list = detail_data['value'].get("oddsHistory").get('hadList', [])
            hhad_list = detail_data['value'].get("oddsHistory").get('hhadList', [])
            crs_list = detail_data['value'].get("oddsHistory").get('crsList', [])
            ttg_list = detail_data['value'].get("oddsHistory").get('ttgList', [])
            hafu_list = detail_data['value'].get("oddsHistory").get('hafuList', [])
        except Exception as e:
            time.sleep(2)
            response = requests.get('https://webapi.sporttery.cn/gateway/jc/football/getFixedBonusV1.qry',
                                    params=params, headers=headers)
            detail_data = response.json()
            had_list = detail_data['value'].get("oddsHistory").get('hadList', [])
            hhad_list = detail_data['value'].get("oddsHistory").get('hhadList', [])
            crs_list = detail_data['value'].get("oddsHistory").get('crsList', [])
            ttg_list = detail_data['value'].get("oddsHistory").get('ttgList', [])
            hafu_list = detail_data['value'].get("oddsHistory").get('hafuList', [])

        if had_list:
            had_list_sorted = sorted(had_list, key=lambda x: (x['updateDate'], x['updateTime']))
            had_combination_desc = get_combination_desc(match_result_list, 'HAD')
            if had_list_sorted:
                first_entry = had_list_sorted[0]
                first_entry['id'] = match_id
                first_entry['win_flag_result'] = str(had_combination_desc[0] if had_combination_desc else "")
                if len(had_list_sorted) == 1:

                    first_entry_n = first_entry.copy()
                    first_entry_n['flag'] = "N"
                    first_entry_y = first_entry.copy()
                    first_entry_y['flag'] = "Y"
                    胜平负固定奖金最终.append(first_entry_n)
                    胜平负固定奖金最终.append(first_entry_y)
                else:

                    first_entry['flag'] = "N"
                    last_entry = had_list_sorted[-1]
                    last_entry['id'] = match_id
                    last_entry['flag'] = "Y"
                    last_entry['win_flag_result'] = str(had_combination_desc[0] if had_combination_desc else "")
                    胜平负固定奖金最终.append(first_entry)
                    胜平负固定奖金最终.append(last_entry)
        if hhad_list:
            hhad_list_sorted = sorted(hhad_list, key=lambda x: (x['updateDate'], x['updateTime']))
            hhad_combination_desc = get_combination_desc(match_result_list, 'HHAD')
            if hhad_list_sorted:
                first_entry = hhad_list_sorted[0]
                first_entry['id'] = match_id
                if isinstance(hhad_combination_desc[0], int):
                    pass
                else:
                    first_entry['win_flag_result'] = str(hhad_combination_desc[0][-1] if hhad_combination_desc else "")
                if len(hhad_list_sorted) == 1:

                    first_entry_n = first_entry.copy()
                    first_entry_n['flag'] = "N"
                    first_entry_y = first_entry.copy()
                    first_entry_y['flag'] = "Y"
                    让胜平负固定奖金最终.append(first_entry_n)
                    让胜平负固定奖金最终.append(first_entry_y)
                else:

                    first_entry['flag'] = "N"
                    last_entry = hhad_list_sorted[-1]
                    last_entry['id'] = match_id
                    last_entry['flag'] = "Y"
                    last_entry['win_flag_result'] = str(hhad_combination_desc[0][-1] if hhad_combination_desc else "")
                    让胜平负固定奖金最终.append(first_entry)
                    让胜平负固定奖金最终.append(last_entry)
        if crs_list:
            process_crs_list(crs_list, match_id,
                             get_combination_desc(match_result_list, 'CRS'))

        if ttg_list:
            b = get_combination_desc(match_result_list, 'TTG')
            process_ttg_list(ttg_list, match_id,
                             b[0])

        if hafu_list:
            process_hafu_list(hafu_list, match_id,
                              get_combination_desc(match_result_list, 'HAFU')[
                                  0])

        insert_odds_data(generate_odds_dataFinal(胜平负固定奖金最终))
        insert_odds_data(generate_hhad_dataFinal(让胜平负固定奖金最终))

        insert_goal_oddsFinal(总进球固定奖金最终)

        insert_half_the_game_tied_final(半全场胜平负固定奖金最终)

        insert_data(generate_data_crsFinal(比分固定奖金最终))

        胜平负固定奖金初始.clear()
        胜平负固定奖金最终.clear()
        让胜平负固定奖金初始.clear()
        让胜平负固定奖金最终.clear()
        比分固定奖金初始.clear()
        比分固定奖金最终.clear()
        总进球固定奖金初始.clear()
        总进球固定奖金最终.clear()
        半全场胜平负固定奖金初始.clear()
        半全场胜平负固定奖金最终.clear()
        time.sleep(0.3)
pool.stop()
